#!/bin/sh
# Select UART Mux: UART Mux for switching between Host and BIC on Slot1 ~ Slot4
# Usage: select-uart-mux <slot1|slot2|slot3|slot4> <host|bic>

REG_OFFSET="0x01"
input_slot=$1
input_target=$2
i2c_bus_id=

show_usage() {
  echo "Usage: select-uart-mux [ slot1 | slot2 | slot3 | slot4 ] [ host | bic ]"
  echo "Select UART Mux"
}

if [ $# -gt 3 ]; then
    show_usage
    exit 255
fi

case $input_slot in
    slot1)
        i2c_bus_id="4"
    ;;
    slot2)
        i2c_bus_id="5"
    ;;
    slot3)
        i2c_bus_id="6"
    ;;
    slot4)
        i2c_bus_id="7"
    ;;
    *)
        echo "Slot must between 1 to 4."
        show_usage
        exit 255
    ;;
    esac

case $input_target in
    host)
        reg_val="0x03"
    ;;
    bic)
        reg_val="0x04"
    ;;
    *)
        echo "Input must be host or bic."
        show_usage
        exit 255
    esac

i2ctransfer -y -f $i2c_bus_id w2@0x0f $REG_OFFSET $reg_val

val=$(i2ctransfer -y -f $i2c_bus_id w1@0x0f $REG_OFFSET r1)
ret=$?

if [ $ret -ne 0 ] || [ "$val" != $reg_val ]; then
    echo "Failed to modify the register value, the register value is $val instead of $reg_val."
    exit 255
fi
